//
//  ZJTextfieldView.m
//
//
//  Created by iOS on 16/6/14.
//  Copyright © 2016年 iOS. All rights reserved.
//

#import "ZJTextfieldView.h"
@interface ZJTextfieldView()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITableView * ZJtableView;
@property (nonatomic,strong)NSMutableArray * tableArray;
@property (nonatomic,assign)BOOL changeFlage;
@property (nonatomic ,strong)UITextField * textfieldResponder;

@end
@implementation ZJTextfieldView
static NSInteger byteNil = 3;
static NSInteger byteNilFlag = 0;
static NSInteger byteNilBank = 4;
static NSInteger byteNilFlagBank = 0;
static NSInteger tableHeight = 30;
static CGFloat  keyHchange = 0;
static CGFloat  keyChangeTableH = 0;
static CGFloat  selfLocation_MAXy = 0;
static NSString * PlistName;
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self addViewTextfiled:frame];
        self.backgroundColor = [UIColor greenColor];
        self.tableArray = [[NSMutableArray alloc]init];
        self.talbeListArray = [[NSMutableArray alloc]init];
        self.changeFlage = NO;
         }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        
        [self addViewTextfiled:self.frame];
        self.backgroundColor = [UIColor greenColor];
        self.tableArray = [[NSMutableArray alloc]init];
        self.talbeListArray = [[NSMutableArray alloc]init];
        self.changeFlage = NO;
    }
    return self;
}
- (void)addViewTextfiled:(CGRect)frame{
    UITextField * textfield = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    self.ZJtextfield = textfield;
    
    textfield.backgroundColor = [UIColor grayColor];
   
    [self addSubview:textfield];
}
#pragma mark 输入的内容改变时调用这个方法  使用时必须实现
- (BOOL)ZJtextField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (self.ZJTextfieldStyle == ZJTextfieldStyleBank) {
        
        return [self bankNumberTextField:textField shouldChangeCharactersInRange:range replacementString:string];
    } if (self.ZJTextfieldStyle == ZJTextfieldStylePhone) {
        return [self phoneNumberTextField:textField shouldChangeCharactersInRange:range replacementString:string];
    }else if (self.ZJTextfieldStyle == ZJTextfieldStyleTableList){
        return NO;
    }else if (self.ZJTextfieldStyle == ZJTextFieldStyleAccount){
        NSString * str = [NSString stringWithFormat:@"%@%@",textField.text,string];
        [self zjtextfiledCountSearchPredicate:str];
        return YES;
    }else{
        return YES;
    }
    
}
#pragma mark 手机号码格式
- (BOOL)phoneNumberTextField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField.text.length >12 && ![string isEqualToString:@""]) {
        return NO;
    }else if ([string isEqualToString:@" "]) {
        NSLog(@"不能输入空格");
        return NO;
    }else if(![string isEqualToString:@""]){
        // NSLog(@"====%@    string = %@",textField.text,string);
        if ((textField.text.length - byteNilFlag)%byteNil == 0 && (textField.text.length - byteNilFlag)/byteNil != 0 && string.length > 0) {
            byteNilFlag = byteNilFlag + byteNil;
            byteNil = 5;
            
            NSMutableString * str = [NSMutableString stringWithFormat:@"%@ ",textField.text];
            textField.text = str;
        }
        NSString * str = [NSString stringWithFormat:@"%@%@",textField.text,string];
        [self zjtextfiledCountSearchPredicate:str];
        return YES;
    }else{
        //删除是遇到空格多删除一位
        if ([[textField.text substringWithRange:range] isEqualToString:@" "]) {
            NSRange deleteRange = NSMakeRange(0, textField.text.length - 1);
            NSString * str = [textField.text substringWithRange:deleteRange];
            textField.text = str;
            
        }
        if (textField.text.length < 3) {
            byteNil = 3;
            byteNilFlag = 0;
        }
        if(textField.text.length  <= byteNilFlag){
            
            byteNilFlag = byteNilFlag - byteNil;
        }
        NSString * str = [NSString stringWithFormat:@"%@%@",textField.text,string];
        [self zjtextfiledCountSearchPredicate:str];
        return YES;
    }
    
}
#pragma mark 银行卡格式化
- (BOOL)bankNumberTextField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //NSLog();
    if (textField.text.length > 19 + 3 && ![string isEqualToString:@""]){
        return NO;
    }else if ([string isEqualToString:@" "]) {
        NSLog(@"不能输入空格");
        return NO;
    }else if(![string isEqualToString:@""]){
        //   NSLog(@"====%@    string = %@",textField.text,string);
        if ((textField.text.length - byteNilFlagBank)%byteNilBank == 0 && (textField.text.length - byteNilFlagBank)/byteNilBank != 0 && string.length > 0) {
            byteNilFlagBank = byteNilFlagBank + byteNilBank;
            byteNilBank = 5;
            
            NSMutableString * str = [NSMutableString stringWithFormat:@"%@ ",textField.text];
            textField.text = str;
        }
        NSString * str = [NSString stringWithFormat:@"%@%@",textField.text,string];
        [self zjtextfiledCountSearchPredicate:str];
        return YES;
        
    }else{
        
        //删除是遇到空格多删除一位
        if ([[textField.text substringWithRange:range] isEqualToString:@" "]) {
            NSRange deleteRange = NSMakeRange(0, textField.text.length - 1);
            NSString * str = [textField.text substringWithRange:deleteRange];
            textField.text = str;
        }
        if (textField.text.length < 4) {
            byteNilBank = 4;
            byteNilFlagBank = 0;
        }
        if(textField.text.length  <= byteNilFlagBank){
            
            byteNilFlagBank = byteNilFlagBank - byteNilBank;
        }
        NSString * str = [NSString stringWithFormat:@"%@%@",textField.text,string];
        [self zjtextfiledCountSearchPredicate:str];
        return YES;
    }
    
    
}
#pragma mark 将字符串中的 @" "全部删除
- (NSString *)ZJtextFiledViewText:(NSString*)string{
    NSArray * array24 = [string componentsSeparatedByString:@" "];
    NSString * str242 = [array24 componentsJoinedByString:@""];
    return str242;
}
#pragma mark 重写get方法
- (NSString*)ZJtext{
    return [self ZJtextFiledViewText:self.ZJtextfield.text];
}
#pragma mark 开始编辑时 创建下拉框
- (void)ZJtextFieldCreateTableviewDidBeginEditing:(UITextField *)textField{
  //  selfLocation_MAXy =  [self selfFrameFromeCurrentMainscreen];
  //  NSLog(@" #### ==%f",selfLocation_MAXy);

    [self keyBordNotifition];
    
    if (self.ZJTextfieldStyle == ZJTextfieldStyleBank) {
        PlistName = @"ZJtextfieldbank";
    }else if (self.ZJTextfieldStyle == ZJTextfieldStylePhone){
        PlistName = @"ZJtextfieldPhone";
    }else{
        PlistName = @"ZJtextfieldOther";
    }
    self.textfieldResponder = textField;
    if (self.ZJTextfieldStyle != ZJTextfieldStyleNone){
        CGRect rect = [self selfFrameRectFromeCurrentMainscreen];
        
        UITableView * tableview = [[UITableView alloc]initWithFrame:CGRectMake(rect.origin.x, rect.origin.y + rect.size.height, CGRectGetWidth(self.ZJtextfield.frame), 5* tableHeight) style:UITableViewStylePlain];
        tableview.backgroundColor = [UIColor orangeColor];
        self.ZJtableView = tableview;
        tableview.delegate = self;
        tableview.dataSource =self;
        [[self parentController].view addSubview:tableview];
        [tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ZJtextfieldTable"];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.ZJTextfieldStyle == ZJTextfieldStyleTableList) {
        return self.talbeListArray.count;
    }else if (self.ZJTextfieldStyle != ZJTextfieldStyleNone && self.ZJTextfieldStyle != ZJTextfieldStyleTableList){
        if (self.tableArray.count <= 5) {
            return self.tableArray.count;
        }else{
            return 5;
        }
    }else{
        return 5;
    }
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ZJtextfieldTable" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor yellowColor];
    if (self.ZJTextfieldStyle == ZJTextfieldStyleTableList) {
        cell.textLabel.text = self.talbeListArray[indexPath.row];
        
    }else{
        cell.textLabel.text = self.tableArray[indexPath.row];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return tableHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.ZJtableView removeFromSuperview];
    if (self.ZJTextfieldStyle == ZJTextfieldStyleTableList) {
        self.ZJtextfield.text = self.talbeListArray[indexPath.row];
    }else{
        self.ZJtextfield.text = self.tableArray[indexPath.row];
    }
    [self.ZJtextfield endEditing:YES];
    NSLog(@" 表 row == %ld",indexPath.row);
}
#pragma mark  建立历史记录
- (void)ZJtextFieldWriteTextDidEndEditing:(UITextField *)textField{
    if (self.ZJTextfieldStyle == ZJTextfieldStyleBank || self.ZJTextfieldStyle == ZJTextfieldStylePhone || self.ZJTextfieldStyle == ZJTextFieldStyleAccount)  {
        NSMutableArray* nameArray = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:PlistName]];
        if (self.ZJtextfield.text.length > 0 && ![nameArray containsObject:self.ZJtextfield.text]) {
            // [nameArray containsObject:self.ZJtextfield.text]
            [nameArray addObject:self.ZJtextfield.text];
        }
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:nameArray forKey:PlistName];
        [self.ZJtableView removeFromSuperview];
        
    }
    [self.ZJtableView removeFromSuperview];
}

#pragma mark 谓词查询
- (void)zjtextfiledCountSearchPredicate:(NSString*)string{
    //@"name BEGINSWITH[c] 'sh'"
    [self.tableArray removeAllObjects];
    NSString * preStr = [NSString stringWithFormat:@"SELF BEGINSWITH[c] '%@'",string];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:preStr];
    NSArray* nameArray = [NSArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:PlistName]];
    for (NSInteger i = 0; i < nameArray.count; i++) {
        if ([predicate evaluateWithObject:nameArray[i]]) {
            [self.tableArray addObject:nameArray[i]];
        }
    }
    [self.ZJtableView reloadData];
}
#pragma mark 取消键盘
- (BOOL)ZJtextFieldShouldReturn:(UITextField *)textField{
    [self.textfieldResponder resignFirstResponder];
    return YES;
}

#pragma mark zjtextfieldtableList 模式下接收到外部数据 刷新表
- (void)setTalbeListArray:(NSMutableArray *)talbeListArray{
    _talbeListArray = talbeListArray;
    if (self.ZJTextfieldStyle == ZJTextfieldStyleTableList) {
        [self.ZJtableView reloadData];
    }
}

#pragma mark 获取当前控制器
- (UIViewController *)parentController
{
    UIResponder *responder = [self nextResponder];
    while (responder) {
        if ([responder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)responder;
        }
        responder = [responder nextResponder];
    }
    return nil;
}
# pragma mark 获取当前控件相对于主屏幕的 frame
- (CGFloat)selfFrameFromeCurrentMainscreen{
    UIViewController * subVC = [self parentController];
    CGRect point = [[self superview] convertRect:self.frame toView:subVC.view];
    return point.origin.y  + point.size.height;
}
- (CGRect)selfFrameRectFromeCurrentMainscreen{
    UIViewController * subVC = [self parentController];
    CGRect point = [[self superview] convertRect:self.frame toView:subVC.view];
    return point;
}

#pragma mark  键盘监听
- (void)keyBordNotifition{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardHide:)
                                                 name:UIKeyboardDidHideNotification
                                               object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notif {
    
    if (self.hidden == YES) {
        return;
    }
    
    if (self.changeFlage == NO) {
        
        if (self.ZJTextfieldStyle == ZJTextfieldStyleNone ) {
            
            keyChangeTableH = 0;
        }else{
            
            keyChangeTableH = 5 * tableHeight;
        }
        
        CGRect rect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat y = rect.origin.y;
        CGFloat keyH = rect.size.height;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.25];
        NSArray *subviews = [[self parentController].view subviews];
        
          CGFloat maxY = [self selfFrameFromeCurrentMainscreen];
        keyHchange = maxY - y + 20;
        
        if (maxY > y - 2) {
            
            [self traverseAllChildControls:subviews AndchangeFlage:YES];
            
            for (UIView *sub in subviews) {
                
                              sub.center = CGPointMake(sub.center.x, sub.center.y -keyHchange - keyChangeTableH);
            }
            selfLocation_MAXy =  keyHchange + keyChangeTableH + selfLocation_MAXy;
            [UIView commitAnimations];
        } else if (maxY < y && maxY > y - 5* tableHeight && self.ZJTextfieldStyle != ZJTextfieldStyleNone){
            
            [self traverseAllChildControls:subviews AndchangeFlage:YES];
            for (UIView *sub in subviews) {
                               sub.center = CGPointMake(sub.center.x, sub.center.y - keyChangeTableH  - keyHchange);
                
            }
            selfLocation_MAXy =  keyHchange + keyChangeTableH + selfLocation_MAXy;
            [UIView commitAnimations];

        }
        
    }
}

- (void)keyboardShow:(NSNotification *)notif {
    if (self.hidden == YES) {
        return;
    }
}

- (void)keyboardWillHide:(NSNotification *)notif {
    if (self.hidden == YES) {
        return;
    }
    
    if (self.changeFlage == YES) {
        if (self.ZJTextfieldStyle == ZJTextfieldStyleNone ) {
            
            keyChangeTableH = 0;
        }else{
            
            keyChangeTableH = 5 * tableHeight;
        }
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.25];
        NSArray *subviews = [[self parentController].view subviews];
        
        [self traverseAllChildControls:subviews AndchangeFlage:NO];
        for (UIView *sub in subviews) {
            
          //  sub.center = CGPointMake(sub.center.x, sub.center.y  + keyHchange + keyChangeTableH);
          
           sub.center = CGPointMake(sub.center.x, sub.center.y  + selfLocation_MAXy);
            NSLog(@" shou ==%f",selfLocation_MAXy);
                  }
        [UIView commitAnimations];
        selfLocation_MAXy = 0;

        //  self.changeFlage = NO;
    }
    
}

- (void)keyboardHide:(NSNotification *)notif {
    if (self.hidden == YES) {
        return;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 递归全部控件寻找到全部的ZJtextfiledview  并且通过kvc 将其的私有属性changFlage 修改
- (void)traverseAllChildControls:(NSArray*)subViews AndchangeFlage:(BOOL)flag{
 
    for (UIView *sub in subViews) {
        if ([sub isKindOfClass:self.class]) {
            if (self.ZJTextfieldStyle != ZJTextfieldStyleNone) {
              [sub setValue:@(flag) forKeyPath:@"self.changeFlage"];
            }else{
                if (sub == self) {
                    [sub setValue:@(flag) forKeyPath:@"self.changeFlage"];
                }else{
                            [sub setValue:@(NO) forKeyPath:@"self.changeFlage"];
                }
            }
           
        }else{
        
            NSArray * array = sub.subviews;
            if (array && array.count > 0) {
                [self traverseAllChildControls:array AndchangeFlage:flag];
            }else{
                continue;
            }
            
        }
    }
}

@end
